import { defineStore } from 'pinia'
import { ref, reactive, toRaw } from 'vue'
import { getMenuList } from '@/api/permission'
import { useRoute, useRouter } from 'vue-router'

export const useUserStore = defineStore('userStore', () => {

    // 用户数据接口
    interface IuserInfo {
        id: number | string
        name: string
    }

    // 路由对象
    const router = useRouter()

    // 当前路由信息
    const route = useRoute()

    // 存储token
    let token = ref<string>()

    // 存储用户信息
    let userInfo = reactive<IuserInfo>({
        id: '',
        name: ''
    })

    // 404页面
    let nPage = [
        {
            name: '404',
            path: '/404',
            component: () => import(/* @vite-ignore */ `../pages/404.vue`)
        },
        { path: '/:pathMatch(.*)', redirect: '/404' }
    ]

    // 已处理成树形菜单
    let menuTree = reactive<any>([])

    // 注册路由数组
    let regRouter = reactive<any>([])

    // 菜单按钮权限组
    let menuBntPermission = reactive<any>([])

    // 获取菜单
    const getMenu = async () => {
        // 获取未处理菜单数据
        let { data } = await getMenuList('/permission/menuList')

        // 处理菜单为树形结构
        let resultTree = createTree(data, 0, [])
        Object.assign(menuTree, resultTree)

        // 处理按钮权限
        await getBntPermisson(data)

        // 注册动态路由
        await addRoutersList(menuTree)

        // 注册404
        await notFound()
    }

    const modules = import.meta.glob("../pages/**/**.vue")

    // 处理菜单为树形结构(过滤不是路由的菜单)
    const createTree = (oList: any, id: number, list: any) => {

        oList.forEach((item: any) => {

            if (item.parent_id == id && item.is_router == 0) {

                // let url = `../pages/${item.url}.vue`;
                // const component = () => import(/* @vite-ignore */url);
                // item.component = component;
                item.component = modules[`../pages/${item.url}.vue`];
                item.path = '/' + item.name
                item.meta = {
                    icon: item.icon,
                    title: item.title
                }

                list.push(item)
            }
        })

        list.forEach((item: any) => {
            item.children = []
            createTree(oList, item.id, item.children)
        })

        return list
    }

    // 注册路由
    const addRoutersList = (data: any) => {

        data.forEach((item: any) => {
            // 注意这里对嵌套路由的处理，children只有重新赋值给children后再push到menuArr，层级才是对的
            if (item.children.length > 0) {

                addRoutersList(item.children)

            } else {
                // // 注意这里路径问题（写成@不行，路径级别也必须对）is_route:0是路由，1按钮
                // let url = `../pages/${item.url}.vue`
                // const component = () => import(/* @vite-ignore */url)
                // item.component = component;
                item.component = modules[`../pages/${item.url}.vue`];
                item.path = '/' + item.name
                regRouter.push(item);
            }

        })

        // 动态添加路由
        regRouter.forEach((item: any) => {
            // 这里必须设置到对应的一级菜单下面
            router.addRoute('home', item);
        });
    }

    // 注册404页面
    const notFound = () => {
        nPage.forEach((item: any) => router.addRoute('home', item))
    }

    // 存储按钮权限
    const getBntPermisson = (data: any) => {
        data.forEach((item: any) => {
            if (item.is_router == 1) {
                menuBntPermission.push(item.name)
            }
        })
    }

    // 退出登录
    const outLoginClearData = () => {
        // 删除注册过的动态路由
        regRouter.forEach((item: any) => router.removeRoute(item.name))
        // 删除404路由
        nPage.forEach((item: any) => router.removeRoute(item.name))
        // 清空tokne
        token.value = ''
        Object.assign(userInfo, {
            id: '',
            name: ''
        })
        menuTree.length = 0
        regRouter.length = 0
        menuBntPermission.length = 0
    }


    // 递归树形路由获取跳转目标路由
    const getPath = (data: any) => {
        if (data.children.length == 0) {
            return data.path
        }
        return getPath(data.children[0])
    }

    // 判断是否跳/（第一次登录成功跳转，根据权限菜单跳转到第一个路由）
    const resultThisRoute = ()=> {
        let targetPath = getPath(menuTree[0])
            return targetPath
    }

    return {
        token,
        userInfo,
        getMenu,
        menuTree,
        outLoginClearData,
        menuBntPermission,
        resultThisRoute
    }

}, {
    persist: true
})